package cn.wolfcode.luowowo.website.controller;

import cn.wolfcode.luowowo.article.domain.Destination;
import cn.wolfcode.luowowo.article.domain.StrategyDetail;
import cn.wolfcode.luowowo.article.domain.Travel;
import cn.wolfcode.luowowo.article.domain.TravelContent;
import cn.wolfcode.luowowo.article.query.TravelQueryObject;
import cn.wolfcode.luowowo.article.service.IDestinationService;
import cn.wolfcode.luowowo.article.service.IStrategyDetailService;
import cn.wolfcode.luowowo.article.service.ITravelService;
import cn.wolfcode.luowowo.cache.service.ITravelStatisVORedisService;
import cn.wolfcode.luowowo.cache.vo.TravelStatisVO;
import cn.wolfcode.luowowo.comment.domain.TravelComment;
import cn.wolfcode.luowowo.comment.query.TravelCommentQuery;
import cn.wolfcode.luowowo.comment.service.ITravelCommentService;
import cn.wolfcode.luowowo.common.exception.LogistException;
import cn.wolfcode.luowowo.common.util.AjaxResult;
import cn.wolfcode.luowowo.common.util.BeanUtil;
import cn.wolfcode.luowowo.member.domain.UserInfo;
import cn.wolfcode.luowowo.website.anno.UserParm;
import cn.wolfcode.luowowo.website.util.UMEditorUploader;
import com.alibaba.dubbo.config.annotation.Reference;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.domain.Page;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.util.List;

@RequestMapping("/travel")
@Controller
public class TravelController {
    @Reference
    private ITravelService travelService;
    @Reference
    private IStrategyDetailService strategyDetailService;
    @Reference
    private IDestinationService destinationService;
    @Reference
    private ITravelCommentService travelCommentService;
    @Reference
    private ITravelStatisVORedisService travelStatisVORedisService;


    @RequestMapping("")
    public String list(@ModelAttribute("qo") TravelQueryObject qo, Model model){
        PageInfo<Travel> pageInfo = travelService.query(qo);
        model.addAttribute("pageInfo",pageInfo);
        return "/travel/list";
    }
    //detail
    @RequestMapping("/detail")
    public Object detail( Model model,Long id,@UserParm UserInfo userInfo){

        //判断是否收藏
        if (userInfo != null){
            model.addAttribute("isFavor", travelStatisVORedisService.isFavor(id,userInfo.getId()));
        }


        //detail
        Travel detail = travelService.selectByPrimaryKey(id);
        TravelContent content = travelService.getContent(id);
        detail.setTravelContent(content);
        model.addAttribute("detail",detail);

        //toasts
        List<Destination> toasts = destinationService.getToasts(detail.getDest().getId());
        Destination dest = toasts.remove(toasts.size() - 1);
        model.addAttribute("dest",dest);
        model.addAttribute("toasts",toasts);
        //sds
        List<StrategyDetail> sds = strategyDetailService.getViewNumTop3(detail.getDest().getId());
        model.addAttribute("sds",sds);
        //ts
        List<Travel> ts = travelService.getViewNumTop3(id);
        model.addAttribute("ts",ts);



        //阅读数+1
        travelStatisVORedisService.viewnumIncrease(id, 1);
        model.addAttribute("vo", travelStatisVORedisService.getTravelStatisVo(id));

        //评论
        TravelCommentQuery query = new TravelCommentQuery();
        query.setTravelId(id);
        query.setPageSize(Integer.MAX_VALUE);
        Page page = travelCommentService.query(query);
        model.addAttribute("list",page.getContent());


        //用户游记总阅读数+1
        travelStatisVORedisService.increaseTotalView(userInfo.getId());

        if (userInfo!=null && userInfo.getId()==detail.getAuthor().getId()){
            model.addAttribute("userInfo1",userInfo);
        }
        return "travel/detail";
    }

    //input
    @RequestMapping("/input")
    public String input( Model model,Long id,@UserParm UserInfo userInfo){
        if (userInfo==null){
            return "redirect:/login.html";
        }
       //dests
        List<Destination> dests = destinationService.getDestsByDeep(3);
        model.addAttribute("dests",dests);

        if (id!=null){
            Travel travel = travelService.selectByPrimaryKey(id);
            TravelContent content = travelService.getContent(id);
            travel.setTravelContent(content);
            model.addAttribute("tv",travel);
        }

        return "/travel/input";
    }

    @Value("${file.path}")
    private String filePath;

    @RequestMapping("/contentImage")
    @ResponseBody
    public String uploadUEImage(MultipartFile upfile, HttpServletRequest request) throws Exception{
        UMEditorUploader up = new UMEditorUploader(request);
        String[] fileType = {".gif" , ".png" , ".jpg" , ".jpeg" , ".bmp"};
        up.setAllowFiles(fileType);
        up.setMaxSize(10000); //单位KB
        up.upload(upfile, filePath);

        String callback = request.getParameter("callback");
        String result = "{\"name\":\""+ up.getFileName() +"\", \"originalName\": \""+ up.getOriginalName() +"\", \"size\": "+ up.getSize()
                +", \"state\": \""+ up.getState() +"\", \"type\": \""+ up.getType() +"\", \"url\": \""+ up.getUrl() +"\"}";
        result = result.replaceAll( "\\\\", "\\\\" );
        if(callback == null ){
            return result ;
        }else{
            return "<script>"+ callback +"(" + result + ")</script>";
        }
    }
    @RequestMapping("/saveOrUpdate")
    @ResponseBody
    public Object  saveOrUpdate(@UserParm UserInfo userInfo,Travel travel){
        if (userInfo== null){
            throw new LogistException("请登录");
        }
        travel.setAuthor(userInfo);
        Long id = travelService.saveOrUpdate(travel);
        return AjaxResult.SUCCESS.addData(id);
    }

    //游记评论
    @RequestMapping("/commentAdd")
    public Object commentAdd(@UserParm UserInfo userInfo, TravelComment travelComment, Model model){
        if (userInfo==null){
            throw new LogistException("请登录");
        }
        travelComment.setUserId(userInfo.getId());
        travelComment.setHeadUrl(userInfo.getHeadImgUrl());
        travelComment.setUsername(userInfo.getNickname());
        travelComment.setLevel(userInfo.getLevel());
        travelComment.setCity(userInfo.getCity());

        travelComment = travelCommentService.save(travelComment);

        //游记回复+1
        travelStatisVORedisService.replynumIncrease(travelComment.getTravelId(), 1);

        //用户游记总回复+1
        travelStatisVORedisService.increaseTotalReply(userInfo.getId());

        model.addAttribute("c",travelComment);
        model.addAttribute("floor",travelCommentService.getContent(travelComment.getTravelId()));
        return "travel/commentTpl";
    }

    //游记收藏
    @RequestMapping("favor")
    @ResponseBody
    public Object favor(Long tid,@UserParm UserInfo userInfo){
        if (userInfo == null){
            AjaxResult result = new AjaxResult(false, "请先登录");
            result.setCode(AjaxResult.RESPONSE_CODE_NOLOGIN);
            return result;
        }
        //如果是true:表示收藏 false:取消收藏
        boolean ret = travelStatisVORedisService.favorByUser(userInfo.getId(),tid);
        //收藏成功
        return new AjaxResult(ret,null)
                .addData(travelStatisVORedisService.getTravelStatisVo(tid));
    }


    //游记点赞
    @RequestMapping("travelThumbup")
    @ResponseBody
    public Object travelThumbup(Long tid, @UserParm UserInfo userInfo){
        if (userInfo == null){
            AjaxResult result = new AjaxResult(false, "请先登录");
            result.setCode(AjaxResult.RESPONSE_CODE_NOLOGIN);
            return result;
        }
        boolean ret = travelStatisVORedisService.travelThumbup(tid,userInfo.getId());
        return new AjaxResult(ret,null)
                .addData(travelStatisVORedisService.getTravelStatisVo(tid));
    }
}
